<?php
class ctrl_base extends framework_base_ctrl
{
	//从caipiaoapi 取订单号；
	private static $_ApiOrderidUrl = API_URL;
	/**
	 * Enter description here ...
	 * @param string $url
	 * @param array $param
	 * @param string $dataType
	 * @param array $header
	 * @param string $method
	 */
    protected static function curl($url, $param,$dataType = '', $header = array(), $method = 'POST') {
        $curl = new framework_base_curl();
        $curl->url = $url;
        $curl->method = $method;
        $curl->params = $param;
        $curl->headers = $header;
        $curl->exec();
        if($dataType == 'json'){
        	$rs_curl = $curl->outputJson(true);
        } else {
        	$rs_curl = $curl->result;
        }
        return  $rs_curl;
    }
    /**
     * 验证必填参数
     * @param type $param
     * @return type
     */
    protected static function getparam($param) {
        $arr = array();
        foreach ($param as $k => $v) {
            if (!isset($_REQUEST[$k]) || framework_static_common::str_empty($_REQUEST[$k])) {
                return array('errcode' => $v);
            }
            $arr[$k] = $_REQUEST[$k];
        }
        return $arr;
    }
    
    protected static function backmsg($code = 0, $data = NULL) {
        $err = include PATH_ERR;
        $arr = array(
            'errcode' => $code,
            'errmsg' => isset($err[$code]) ? $err[$code]['msg'] : '未知错误',
            'lv' => isset($err[$code]) ? $err[$code]['lv'] : 1,
            'close' => isset($err[$code]) ? $err[$code]['close'] : 1,
            'data' => $data,
        );
        exit(json_encode($arr));
    }
     /**
     * 页面中返回
     * @param type $code
     * @param type $islink
     * @param type $url
     */
    protected static function backpage($code = 1, $islink = FALSE, $url = '') {
        $err = include PATH_ERR;
        $msg = isset($err[$code]) ? $err[$code]['msg'] : '未知错误';
        if ($islink) {
            if (framework_static_common::str_empty($url)) {
                exit("<script>alert('{$msg}');history.back(-1);location.href = document.referrer;</script>");
            } else {
                exit("<script>alert('{$msg}');location.href = '{$url}';</script>");
            }
        } else {
            exit("<script>alert('{$msg}');</script>");
        }
    }
    /**
     * 生成统一订单号码 22位
     * @return type
     */
    public static function getOrderId() {
    	$result = self::curl(self::$_ApiOrderidUrl,array('act'=>'service','st'=>'get_order_id'),'',array(),'GET');
		framework_static_function::write_log("订单id:".$result,"orderId");
		$results = json_decode($result,TRUE);
		$orderId = $results['data']['order_id'];
		if($results['code'] == '200'&&!empty($orderId)){
			 return $orderId;
		}else{
			 return date('YmdHis') . substr(microtime(), 2, 4) . rand(1000, 9999);
		}
    }	
	/**
     * 生成统一追号订单号码
     * @return type
     */
    public static function getChaseId() {
    	try {
	   		$result = self::curl(self::$_ApiOrderidUrl,array('act'=>'service','st'=>'get_zh_sn'),'',array(),'GET');
			framework_static_function::write_log("获取追号id_1:".$result,"ChaseId");
			$results = json_decode($result,TRUE);
			$chaseId = $results['data']['order_id'];
			if($results['code'] == '200'&&!empty($chaseId)){
				return $chaseId;
			}else{
				return "ZH".uniqid().'w';
			}
		} catch(Exception $e) {
			$result = self::curl(self::$_ApiOrderidUrl,array('act'=>'service','st'=>'get_zh_sn'),'',array(),'GET');
			framework_static_function::write_log("获取追号id_2:".$result,"ChaseId");
			$results = json_decode($result,TRUE);
			$chaseId = $results['data']['order_id'];
			if($results['code'] == '200'&&!empty($chaseId)){
				return $chaseId;
			}else{
				return "ZH".uniqid().'w';
			}
		}
    }	
    /**
     * 接口中返回
     * @param type $code
     * @param type $data
     */
    protected static function backapi($code = 0, $data = NULL) {
        $err = include PATH_ERR;
        $arr = array(
            'errcode' => $code,
            'errmsg' => isset($err[$code]) ? $err[$code] : '未知错误',
            'data' => $data,
        );
        exit(json_encode($arr));
    }
	/**
	 * 返还错误提示信息 
	 * $code 错误代码
	 * $data 错误提示信息
	 */
	 protected static function backcodemsg($code) {
	 	$err = include PATH_ERR;
	 	$arr = array(
            'errcode' => $code,
            'errmsg' => isset($err[$code]) ? $err[$code] : '未知错误',
        );
        framework_static_function::write_log("支付宝失败:".$code,"zfb");
        if(is_array($arr['errmsg'])) {
			return $arr['errmsg']['msg'];
        }else {
        	return $arr['errmsg'];
        }
	 }
	 /**
	 * ajax.post 清除缓存 
	 */
	 protected static function clearcache(){
    	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
        header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache"); // HTTP/1.0
	 }

    /**
     * 获取当前页面的完整网址
     * ex-chendeng001
     * @return string
     */
    public static function get_url() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    }
    /**
     * 将字符串进行加密
     * @author guohui 2013/12/02 15:45
     * @param code string 要加密的字符串
     * @return str string 加密后的字符串
     *
     */
    public static function strencrypt($code) {
        if(!class_exists('static_aes')) {
            include_once(PATTH_FRAMEWORK.DIRECTORY_SEPARATOR.'static'.DIRECTORY_SEPARATOR.'aes.class.php');
        }
        $aes = new static_aes();
        $aes->set_key('AKlMU89D3FchIkhK');
        $aes->require_pkcs5();
        $rt = $aes->encrypt($code);
        return $rt;
    }

    /**
     * 将加密字符串进行解密
     * @author guohui 2013/12/02 15:45
     * @param code string 要解密的字符串
     * @return str string 解密后的字符串
     *
     */
    public static function strdecrypt($code) {
        if(!class_exists('static_aes')) {
            include_once(PATTH_FRAMEWORK.DIRECTORY_SEPARATOR.'static'.DIRECTORY_SEPARATOR.'aes.class.php');
        }
        $aes = new static_aes();
        $aes->set_key('AKlMU89D3FchIkhK');
        $aes->require_pkcs5();
        $rt = $aes->decrypt($code);
        return $rt;
    }
    /**
     * 获取/检测微信用户登录状态
     */
    public static function weixin_check_login() {
    	//获取open_id 走用户体系取 user_id
    	if(empty($_SESSION['wx_userinfo']['openid'])) {
    		setcookie('backurl',HOST_URL.'/?'.$_SERVER['QUERY_STRING'],0);
    		ctrl_weixin::oauth();
    	}else{//刷新用户信息，解决用户未注销，不能及时获取用户类型问题。
    		$userinfo = model_user::get_userinfo($_SESSION['wx_userinfo']['openid']);
            $_SESSION['wx_userinfo'] = $userinfo;
    		setcookie('backurl','');
    		unset($_SESSION['backurl']);
    	}
    }
    
}
